<?php
/**
 * HTTP客户端类
 */

namespace LicenseSDK\Http;

use LicenseSDK\Exceptions\LicenseException;

class Client
{
    /**
     * API基础URL
     * @var string
     */
    private $baseUrl;
    
    /**
     * 超时时间（秒）
     * @var int
     */
    private $timeout;
    
    /**
     * 构造函数
     * 
     * @param string $baseUrl
     * @param int $timeout
     */
    public function __construct($baseUrl, $timeout = 10)
    {
        $this->baseUrl = rtrim($baseUrl, '/');
        $this->timeout = $timeout;
    }
    
    /**
     * POST请求
     * 
     * @param string $path
     * @param array $data
     * @return array
     * @throws LicenseException
     */
    public function post($path, array $data = [])
    {
        $url = $this->baseUrl . $path;
        
        // 优先使用curl
        if (function_exists('curl_init')) {
            return $this->curlPost($url, $data);
        }
        
        // 备选：file_get_contents
        if (ini_get('allow_url_fopen')) {
            return $this->filePost($url, $data);
        }
        
        throw new LicenseException('无法发送HTTP请求，请启用curl或allow_url_fopen');
    }
    
    /**
     * GET请求
     * 
     * @param string $path
     * @param array $params
     * @return array
     * @throws LicenseException
     */
    public function get($path, array $params = [])
    {
        $url = $this->baseUrl . $path;
        
        if (!empty($params)) {
            $url .= '?' . http_build_query($params);
        }
        
        if (function_exists('curl_init')) {
            return $this->curlGet($url);
        }
        
        if (ini_get('allow_url_fopen')) {
            return $this->fileGet($url);
        }
        
        throw new LicenseException('无法发送HTTP请求，请启用curl或allow_url_fopen');
    }
    
    /**
     * 使用CURL发送POST请求
     * 
     * @param string $url
     * @param array $data
     * @return array
     * @throws LicenseException
     */
    private function curlPost($url, array $data)
    {
        $ch = curl_init();
        
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, $this->timeout);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/x-www-form-urlencoded',
            'User-Agent: LicenseSDK/' . \LicenseSDK\LicenseValidator::VERSION,
        ]);
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $error = curl_error($ch);
        
        curl_close($ch);
        
        if ($error) {
            throw new LicenseException('HTTP请求失败: ' . $error);
        }
        
        if ($httpCode !== 200) {
            throw new LicenseException('HTTP请求失败，状态码: ' . $httpCode);
        }
        
        return $this->parseResponse($response);
    }
    
    /**
     * 使用CURL发送GET请求
     * 
     * @param string $url
     * @return array
     * @throws LicenseException
     */
    private function curlGet($url)
    {
        $ch = curl_init();
        
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, $this->timeout);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'User-Agent: LicenseSDK/' . \LicenseSDK\LicenseValidator::VERSION,
        ]);
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $error = curl_error($ch);
        
        curl_close($ch);
        
        if ($error) {
            throw new LicenseException('HTTP请求失败: ' . $error);
        }
        
        if ($httpCode !== 200) {
            throw new LicenseException('HTTP请求失败，状态码: ' . $httpCode);
        }
        
        return $this->parseResponse($response);
    }
    
    /**
     * 使用file_get_contents发送POST请求
     * 
     * @param string $url
     * @param array $data
     * @return array
     * @throws LicenseException
     */
    private function filePost($url, array $data)
    {
        $options = [
            'http' => [
                'method' => 'POST',
                'header' => "Content-Type: application/x-www-form-urlencoded\r\n" .
                           "User-Agent: LicenseSDK/" . \LicenseSDK\LicenseValidator::VERSION . "\r\n",
                'content' => http_build_query($data),
                'timeout' => $this->timeout,
            ],
        ];
        
        $context = stream_context_create($options);
        $response = @file_get_contents($url, false, $context);
        
        if ($response === false) {
            $error = error_get_last();
            throw new LicenseException('HTTP请求失败: ' . ($error['message'] ?? 'Unknown error'));
        }
        
        return $this->parseResponse($response);
    }
    
    /**
     * 使用file_get_contents发送GET请求
     * 
     * @param string $url
     * @return array
     * @throws LicenseException
     */
    private function fileGet($url)
    {
        $options = [
            'http' => [
                'method' => 'GET',
                'header' => "User-Agent: LicenseSDK/" . \LicenseSDK\LicenseValidator::VERSION . "\r\n",
                'timeout' => $this->timeout,
            ],
        ];
        
        $context = stream_context_create($options);
        $response = @file_get_contents($url, false, $context);
        
        if ($response === false) {
            $error = error_get_last();
            throw new LicenseException('HTTP请求失败: ' . ($error['message'] ?? 'Unknown error'));
        }
        
        return $this->parseResponse($response);
    }
    
    /**
     * 解析响应
     * 
     * @param string $response
     * @return array
     * @throws LicenseException
     */
    private function parseResponse($response)
    {
        $data = json_decode($response, true);
        
        if (json_last_error() !== JSON_ERROR_NONE) {
            throw new LicenseException('响应解析失败: ' . json_last_error_msg());
        }
        
        // 统一的响应格式
        if (isset($data['code'])) {
            if ($data['code'] == 200) {
                return [
                    'success' => true,
                    'message' => $data['msg'] ?? 'Success',
                    'data' => $data['data'] ?? [],
                ];
            } else {
                return [
                    'success' => false,
                    'message' => $data['msg'] ?? 'Error',
                    'error_code' => $data['code'],
                    'data' => $data['data'] ?? [],
                ];
            }
        }
        
        return $data;
    }
}

